const express = require('express')
// 生成ID
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs');
const axios = require('axios');
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt');
const multer = require('multer');
let fs = require('fs')
const config = require('../../config/baseinfo')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
const router = express.Router()
// 一级路由： /user
// 二级路由： /register
// http://127.0.0.1:3005/user/register
// 导入已封装的数据函数
const db = require('../../config/db.js')
const number = require('../../utils/number.js')

// 增加数据(注册)
router.post('/register', async function (req, res) {
    console.log(req.body);
    let id = uuidv4() || Math.random().toString().slice(2);
    let userName = req.body.userName; // 用户名
    let passWord = req.body.passWord; // 密码
    let role = req.body.role; //  角色
    let phone = req.body.phone; //  手机号
    let time = dayjs().format('YYYYMMDDHHmmss');
    let jobnumber = await number(role) //  设置工号
    console.log('jobnumber', jobnumber);
    // 查询用户表
    let user_check_sql = 'select * from user where phone = "' + phone + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            // 解构赋值(数据库)
            if (rows && rows.length != 0) {
                let [user] = rows;
                if (user.phone == phone) {
                    res.send({
                        code: 201,
                        msg: '账号已存在'
                    })
                } else {
                    res.send({
                        code: 501,
                        msg: '后端异常'
                    })
                }
            }
            else {
                // 添加用户
                let user_insert_sql = 'insert into User(userName,passWord,id,role,phone,time,jobnumber) values(' + '"' + userName + '"' + ',' + '"' + passWord + '"' + ',' + '"' + id + '"' + ',' + '"' + role + '"' + ',' + '"' + phone + '"' + ',' + '"' + time + '"' + ',' + '"' + jobnumber + '"' + ')';
                db.query(user_insert_sql, (err) => {
                    if (err) {
                        res.send({
                            code: -1,
                            msg: '注册失败',
                            err: err,
                        })
                    } else {
                        res.send({
                            data: {
                                code: 200,
                                msg: '注册成功',
                                userName: userName,
                                success: true
                            }
                        });
                    }
                })
            }

        }
    })
})

// 查询数据(登录)
router.post('/login', function (req, res) {
    // let userName = req.body.userName;
    let passWord = req.body.passWord;
    let role = req.body.role;
    let phone = req.body.phone;
    // console.log(role, phone);
    // 查询用户表
    let user_check_sql = 'select * from user where passWord="' + passWord + '" and phone = "' + phone + '" and role = "' + role + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '登录失败',
                err: err,
            })
        } else {
            if (rows && rows.length == 0) {
                res.send({
                    code: 404,
                    msg: '账号或密码错误'
                });
            } else {

                let [{ id, userName, role, phone, avatar,jobnumber }] = rows;
                // 将用户id传入并生成token
                let jwt = new JwtUtil(id);
                // 获取token
                let token = jwt.generateToken();
                let user_update_sql = 'update user set token = "' + token + '" where id="' + id + '"';
                db.query(user_update_sql, (err, rows) => {
                    if (err) {
                        res.send({
                            code: -1,
                            msg: '修改失败',
                            err: err
                        })

                    } else {

                        res.send({
                            data: {
                                code: 200,
                                success: true,
                                msg: '登录成功',
                                accessToken: token,
                                refreshToken: token,
                                data: {
                                    userName,
                                    role,
                                    phone,
                                    avatar,
                                    jobnumber
                                }
                            }
                        })
                    }
                })
                // 将 token 返回给客户端
            }
        }
    })
})
// 修改个人信息
router.put('/profile', function (req, res) {
    // 请求需要进行token校验 
    console.log(req.headers);
    console.log(req.body.values);
    let token = req.headers.etoken;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    console.log(result.data);
    // 接收前端的参数
    if (result == 'err') {
        res.status(401).send({
            code: 3002,
            msg: '登录已过期,请重新登录'
        })
    } else {
        // 接收前端的文件
        let info = req.body.values
        // 定义存在在服务器的图片的路径（存在数据库的路径）
        // let image = `${HostUrl}/static/upload/${file.filename}`
        let id = result.data;
        let user_check_sql = "select * from user where id='" + id + "'";
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败',
                    err
                })
            } else {
                if (rows && rows.length != 0) {
                    var user_update_sql = "update user set avatar = '" + info.avatar + "',userName = '" + info.userName + "',phone = '" + info.phone + "',gender = '" + info.gender + "' where  id = '" + id + "'";
                    db.query(user_update_sql, function (err, rows) {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: "设置失败",
                                err
                            });
                        } else {
                            res.send({
                                data: {
                                    code: 200,
                                    msg: "设置成功",
                                    success: true,
                                }
                            });
                        }
                    });
                }
            }
        })
    }
})
// 获取个人信息
router.get('/userinfor', function (req, res) {
    // 前端接收参数
    // let token = req.query.token;
    // 请求需要进行token校验 
    // console.log(req.headers);
    let token = req.headers.etoken;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    // console.log(result.data);
    let id = result.data;
    // 查询用户表
    let user_check_sql = 'select * from user where id="' + id + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            // console.log(rows);
            let [{ userName, gender, jobnumber, phone, avatar }] = rows;
            console.log(typeof avatar);
            res.send({
                data: {
                    code: 200,
                    msg: '查询成功',
                    success: true,
                    data: {
                        userName,
                        gender,
                        phone,
                        avatar,
                        jobnumber,
                    }
                }
            })
        }
    })
})
// 修改密码数据
router.put('/updatepwd', function (req, res) {
    // 请求需要进行token校验 
    // console.log(req.headers);
    console.log(req.body.values);
    let token = req.headers.etoken;
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            let pwd = req.body.values;
            let id = result.data;
            let user_check_sql = 'select * from user where id = "' + id + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '查询失败'
                    })
                } else {
                    if (rows && rows.length != 0) {
                        let [{ passWord }] = rows;
                        // console.log('passWord', passWord);
                        if (pwd.oldpassWord !== passWord) {
                            res.send({
                                data: {
                                    code: -1,
                                    msg: '旧密码不正确',
                                    success: false
                                }
                            })
                        } else {
                            let user_update_sql = 'update user set passWord = "' + pwd.passWord + '" where id="' + id + '"';
                            db.query(user_update_sql, function (err) {
                                if (err) {
                                    res.send({
                                        data: {
                                            code: -1,
                                            msg: "修改密码失败",
                                            success: false,
                                            err,
                                        }
                                    });
                                } else {
                                    res.send({
                                        data: {
                                            code: 200,
                                            msg: "修改密码成功",
                                            success: true,
                                        }
                                    });
                                }
                            });

                        }
                    }

                }
            })
        }
    }


})

// 微信登录/注册
router.post('/login/wx', async (req, res, next) => {
    try {
        const { code } = req.body
        // 当前微信开发者的appId
        const appId = 'wx8a955c69deb4dc0c'
        const appSecret = 'fb12d3748e093027e9651ff8192175a4';
        // 微信登录的第三方接口
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
        //调用微信登录第三方接口
        const { data: { openid, session_key } } = await axios({ url, method: 'get' })
        // const data = await axios({ url, method: 'get' })
        // console.log(data);
        //更新当前用户的信息
        // 查询用户表
        let user_check_sql = 'select * from wxuser where openid="' + openid + '"';
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败'
                })
            } else {
                // 解构赋值(数据库)
                if (rows && rows.length != 0) {
                    let [user] = rows;
                    if (user.openid == openid) {
                        // 将用户id传入并生成token
                        let jwt = new JwtUtil(openid);
                        // 获取token
                        let token = jwt.generateToken();
                        res.send({
                            data: {
                                code: 200,
                                msg: '登录成功',
                                accessToken: token,
                                refreshToken: token
                            },
                            success: true
                        })
                    } else {
                        res.send({
                            code: 501,
                            msg: '后端异常'
                        })
                    }
                }
                else {
                    let userId = uuidv4() || Math.random().toString().slice(2);
                    let username = '新用户';
                    let avgPath = 'http://localhost:3005/public/images/wxuser.png'
                    // 添加用户
                    let user_insert_sql = 'insert into Wxuser(openid,session_key,userId,username,avgPath) values(' + '"' + openid + '"' + ',' + '"' + session_key + '"' + ',' + '"' + userId + '"' + ',' + '"' + username + '"' + ',' + '"' + avgPath + '"' + ')';
                    db.query(user_insert_sql, (err) => {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: '登录失败',
                                err: err,
                            })
                        } else {
                            // 将用户id传入并生成token
                            let jwt = new JwtUtil(openid);
                            // 获取token
                            let token = jwt.generateToken();
                            res.send({
                                data: {
                                    code: 200,
                                    msg: '登录成功',
                                    accessToken: token,
                                    refreshToken: token
                                },
                                success: true
                            });
                        }
                    })
                }

            }
        })
    } catch {
        next({ message: '接口错误' })
    }
});

// 获取微信用户信息
router.get('/current/info', function (req, res) {
    // 前端接收参数
    // let token = req.query.token;
    // 请求需要进行token校验 
    // console.log(req);
    // console.log(req.headers);
    let token = req.headers.etoken;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    // console.log(result.data);
    let openid = result.data;
    // 查询用户表
    let user_check_sql = 'select * from wxuser where openid="' + openid + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            console.log(rows);
            let [info] = rows;
            // console.log(typeof address);
            let userInfo = {
                username: info.username,
                userId: info.userId,
                realName: info.realName,
                gender: info.gender,
                avgPath: info.avgPath,
                areaCode: info.areaCode,
            }
            res.send({
                data: userInfo,
                code: 200,
                msg: '查询成功',
                success: true
            })

        }
    })
})

// 修改微信用户信息
router.put('/wxprofile', function (req, res) {
    // 请求需要进行token校验 
    // console.log(req.headers);
    console.log(req.body);
    let token = req.headers.etoken;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    console.log(result.data);
    // 接收前端的参数
    if (result == 'err') {
        res.status(401).send({
            code: 3002,
            msg: '登录已过期,请重新登录'
        })
    } else {
        // 接收前端的文件
        let info = req.body
        // 定义存在在服务器的图片的路径（存在数据库的路径）
        // let image = `${HostUrl}/static/upload/${file.filename}`
        let openid = result.data;
        let user_check_sql = "select * from wxuser where openid='" + openid + "'";
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败',
                    err
                })
            } else {
                if (rows && rows.length != 0) {
                    var user_update_sql;
                    if(info.avgPath){
                        user_update_sql = "update wxuser set avgPath = '" + info.avgPath + "' where  openid = '" + openid + "'";
                    }
                    else if(info.username){
                        user_update_sql = "update wxuser set username = '" + info.username + "' where  openid = '" + openid + "'";
                    }
                    else if(info.realName){
                        user_update_sql = "update wxuser set realName = '" + info.realName + "' where  openid = '" + openid + "'";
                    }
                    else if(info.gender){
                        user_update_sql = "update wxuser set gender = '" + info.gender + "' where  openid = '" + openid + "'";
                    }
                    else if(info.areaCode){
                        user_update_sql = "update wxuser set areaCode = '" + info.areaCode + "' where  openid = '" + openid + "'";
                    }
                    db.query(user_update_sql, function (err, rows) {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: "设置失败",
                                err
                            });
                        } else {
                            res.send({
                                data: {},
                                code: 200,
                                msg: "设置成功",
                                success: true,
                            });
                        }
                    });
                }
            }
        })
    }
})
module.exports = router;
